package com.baizhi.yyl.service;

import com.baizhi.yyl.dao.AdminDao;
import com.baizhi.yyl.entity.Admin;
import com.baizhi.yyl.utils.ImageCodeUtil;
import com.baizhi.yyl.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class AdminServiceImpl implements AdminService{
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RedisTemplate redisTemplate;

    // 生成验证码
    public Map<String,String> getImageCodes(String sessionId){
        Map<String,String> map = new HashMap<>();
        try {
            String securityCode = ImageCodeUtil.getSecurityCode();
            System.out.println(securityCode);

            // 往redis中存验证码
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set("CODE_" + sessionId, securityCode, 2, TimeUnit.MINUTES);
            System.out.println("getImageCodes: CODE_" + sessionId);

            String imgBase64 = ImageCodeUtil.careateImgBase64(securityCode);
            map.put("token", sessionId);
            map.put("imgCode", imgBase64);
            return map;
        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    @Override
    public Map<String,String> login(Admin admin, String token) {
        System.out.println("in login..... " + admin);
        System.out.println(token);
        Map<String,String> map = new HashMap<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOperations = redisTemplate.opsForValue();

        Object serverCode = valueOperations.get("CODE_" + token);
        System.out.println(serverCode);
        System.out.println("login: CODE_" + token);

        // 验证码不正确
        if (serverCode == null){
            map.put("state","error");
            map.put("message","验证码已过期！");
            return map;
        } else {
            if (!admin.getEnCode().equals(serverCode)){
                map.put("state","error");
                map.put("message","验证码不正确！");
                return map;
            }
        }
        // 验证码正确，则检查帐号密码
        Admin user = adminDao.selectByUsername(admin.getUsername());
        if (user == null){  // 帐户不存在
            //System.out.println("用户名不存在！");
            map.put("state","error");
            map.put("message","用户名不存在！");
        } else {  // 帐户存在
            if (user.getStatus().equals("0")){
                map.put("state","error");
                map.put("message","该用户已被冻结！");
                return map;
            }
            // 获取随机盐
            String salt = user.getSalt();
            // 对 当前输入的密码 加盐 加md5
            String password = admin.getPassword();
            String md5Code = Md5Utils.getMd5Code(salt + password + salt);

            if (user.getPassword().equals(md5Code)) {
                System.out.println("ok！ " + token);
                map.put("state", "success");
                map.put("message", token);

                // 往redis中存token(以sessionid为key， 当前用户信息为value)
                valueOperations.set("TOKEN_" + token, admin, 30, TimeUnit.MINUTES);
            } else {
                System.out.println("密码错误！");
                map.put("state", "error");
                map.put("message", "密码错误！");
            }
        }
        return map;
    }
    // 获取用户信息
    public Admin getUserInfo(String token){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOperations = redisTemplate.opsForValue();
        return (Admin) valueOperations.get("TOKEN_" + token);
    }

    @Override
    @Transactional
    public void register(Admin admin) {
        String password = admin.getPassword();
        String salt = Md5Utils.getSalt(6); // 调用工具类获取随机盐
        String md5Pwd = Md5Utils.getMd5Code(salt+password+salt);//调用工具类md5加密
        System.out.println("原密码：" + password);
        System.out.println("原密码的md5加密：" + Md5Utils.getMd5Code(password));
        System.out.println("随机盐："+salt);
        System.out.println("加盐后密码的md5加密：" + md5Pwd);
        admin.setPassword(md5Pwd);
        admin.setSalt(salt);

        adminDao.insert(admin);
    }

    public void logout(String token){
        // 从redis中存token(以sessionid为key， 当前用户信息为value)
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.delete("TOKEN_" + token);
    }
}
